package com.autumn.mybatis.mapper;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.mapping.MappedStatement;

/**
 * 映射帮助
 * 
 * @author 杨昌国
 *
 *         2017-10-11 18:16:32
 */
public class MapperUtils {

	private final static String DOT = ".";

	/**
	 * mappedStatement 实体缓存
	 */
	private final static Map<String, Class<?>> mappedMapperClassMap = new ConcurrentHashMap<>();

	/**
	 * 获取 MappedStatement 接口 Mapper 类
	 *
	 * @param msId
	 *            MappedStatement is id
	 * @return
	 */
	public static Class<?> getMapperClass(String msId) {
		if (msId.indexOf(DOT) == -1) {
			throw new MapperException("id 为 " + msId + " 的 MappedStatement 的 id = " + msId + ",不符合规范格式。");
		}
		String mapperClassStr = msId.substring(0, msId.lastIndexOf("."));
		return mappedMapperClassMap.computeIfAbsent(mapperClassStr, (key) -> {
			try {
				return Class.forName(key);
			} catch (ClassNotFoundException e) {
				throw new MapperException("MappedStatement  id =" + msId + " 的 MapperClass 类不存在。");
			}
		});
	}

	/**
	 * 根据 MappedStatement 的 Id 获取方法名
	 *
	 * @param msId
	 *            MappedStatement is id
	 * @return
	 */
	public static String getMethodName(String msId) {
		return msId.substring(msId.lastIndexOf(".") + 1);
	}

	/**
	 * 获取 MappedStatement 执行的方法名
	 *
	 * @param ms
	 *            MappedStatement
	 * @return
	 */
	public static String getMethodName(MappedStatement ms) {
		return getMethodName(ms.getId());
	}

}
